//
//  BaseTabBarViewController.m
//  HuaRun
//
//  Created by admin on 17/8/28.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "BaseTabBarViewController.h"
#import "HomePageViewController.h"
#import "ContactPersonViewController.h"
#import "CompanyViewController.h"
#import "MeetingViewController.h"

#import "BaseSearchViewController.h"
#import "UIImage+Image.h"
#import "UIView+Frame.h"
#import "Contact_CusTableViewController.h"
#import "Contact_DetailViewController.h"
#import "AddViewController.h"
//测试用
#import "TestViewController.h"
#import "PopAddContentView.h"
#import "Add_Manual_CompanyViewController.h"
#import "Add_Manual_ContactViewController.h"
#import "ZLGestureLockViewController.h"

#import "TZImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"

#import "UserModel.h"
#import "LoginViewController.h"
#import "Contact_DetailModel.h"
#import "XHNHudManager.h"
#import "ImageLabView.h"
#import "BaseNavigationController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "TouchLockViewController.h"

@interface BaseTabBarViewController ()<UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, TZImagePickerControllerDelegate, UITabBarControllerDelegate, UIAlertViewDelegate>

@property (nonatomic, strong)PopAddContentView * popAddView;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
@property (strong, nonatomic) CLLocation *location;

@property (nonatomic,assign) NSInteger lastSelectedIndex;

//继续添加图片弹窗
@property (strong, nonatomic) UIAlertView * continuAlertView;

//是否已经上传一张图片
@property (assign, nonatomic) BOOL isAlreadyUpload;
//保存获取到的数据
@property (strong, nonatomic) Contact_DetailModel *firstDetailModel;

@end

@implementation BaseTabBarViewController
#pragma mark -- life cycle
- (void)dealloc {
    NSLog(@"%@ dealloc", [self class]);

    //取消定时器
    [_timer invalidate];
    _timer = nil;
}

//页面将要进入前台，开启定时器
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //开启定时器
//    [_timer setFireDate:[NSDate distantPast]];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //关闭定时器
//    [_timer setFireDate:[NSDate distantFuture]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configureViewControllers];
    [self addCameraButton];

    [self globalAppearanceConfig];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginVC:) name:kNotificationShowLoginVC object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetTabbarTitle) name:kNotificationResetLanguage object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fetchRefreshTokenMethod) name:kNotificationRefrshToken object:nil];

//    //每55分钟刷新一次refershtoken
    self.timer = [NSTimer scheduledTimerWithTimeInterval:55 * 60 target:self selector:@selector(fetchRefreshTokenMethod) userInfo:nil repeats:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configureViewControllers {
    
//    [[UITabBar appearance] setBarStyle:UIBarStyleDefault];

    HomePageViewController * homePageVC = [[HomePageViewController alloc] init];
    homePageVC.title = NSLocalizedString(@"首页", nil);
    homePageVC.tabBarItem.image = [UIImage imageNamed:@"icon_button_Home_page_huise"];
    homePageVC.tabBarItem.selectedImage = [UIImage imageWithOriginalRenderingMode:@"icon_button_Home_page"];
    UINavigationController * homePageNav = [[UINavigationController alloc] initWithRootViewController:homePageVC];
    
    CompanyViewController * companyVC = [[CompanyViewController alloc] init];
    companyVC.title = NSLocalizedString(@"公司", nil);
    companyVC.tabBarItem.image = [UIImage imageNamed:@"icon_button_company01"];
    companyVC.tabBarItem.selectedImage = [UIImage imageWithOriginalRenderingMode:@"icon_button_company_xuanzhong"];
    UINavigationController * companyNav = [[UINavigationController alloc] initWithRootViewController:companyVC];
    
    AddViewController * addVC = [AddViewController new];
    addVC.tabBarItem.enabled = NO;
    UINavigationController * addNav = [[UINavigationController alloc] initWithRootViewController:addVC];

    ContactPersonViewController * contactPersonVC = [[ContactPersonViewController alloc] init];
    contactPersonVC.title = NSLocalizedString(@"联系人", nil);
    contactPersonVC.tabBarItem.image = [UIImage imageNamed:@"icon_button_contact01"];
    contactPersonVC.tabBarItem.selectedImage = [UIImage imageWithOriginalRenderingMode:@"icon_button_contact_yanse"];
    UINavigationController * contactPersonNav = [[UINavigationController alloc] initWithRootViewController:contactPersonVC];
    
    MeetingViewController * meetingVC = [[MeetingViewController alloc] init];
    meetingVC.title = NSLocalizedString(@"会议", nil);
    meetingVC.tabBarItem.image = [UIImage imageNamed:@"icon_button_meeting01"];
    meetingVC.tabBarItem.selectedImage = [UIImage imageWithOriginalRenderingMode:@"icon_button_meeting_xuanzhopng"];
    UINavigationController * meetingNav = [[UINavigationController alloc] initWithRootViewController:meetingVC];
    
    self.delegate = self;
    _lastSelectedIndex = 0;

    self.viewControllers = @[homePageNav, companyNav, addNav, contactPersonNav,meetingNav];
}

//重新设置title
- (void)resetTabbarTitle{
    
    UINavigationController * homePageNav = self.viewControllers[0];
    HomePageViewController * homePageVC = homePageNav.viewControllers[0];
    homePageVC.title = NSLocalizedString(@"首页", nil);
    [homePageVC.tableView reconfigureHeaderTips];
    
    UINavigationController * companyNav = self.viewControllers[1];
    CompanyViewController * companyVC = companyNav.viewControllers[0];
    companyVC.title = NSLocalizedString(@"公司", nil);
    [companyVC.tableView reconfigureHeaderTips];

    UINavigationController * contactPersonNav = self.viewControllers[3];
    ContactPersonViewController * contactPersonVC = contactPersonNav.viewControllers[0];
    contactPersonVC.title = NSLocalizedString(@"联系人", nil);
    [contactPersonVC.tableView reconfigureHeaderTips];

    UINavigationController * meetingNav = self.viewControllers[4];
    MeetingViewController * meetingVC = meetingNav.viewControllers[0];
    meetingVC.title = NSLocalizedString(@"会议", nil);
    [meetingVC.tableView reconfigureHeaderTips];
 
    [homePageVC resetLabelLanguge];
}

#pragma mark ---- <添加按钮>
- (void)addCameraButton {
    
    UIButton *cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [cameraBtn setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    [cameraBtn setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateHighlighted];
    
    // 自适应,自动根据按钮图片和文字计算按钮尺寸
    [cameraBtn sizeToFit];
    
    cameraBtn.center = CGPointMake(self.tabBar.xj_width * 0.5, self.tabBar.xj_height * 0.5 - kMargin10);
    [cameraBtn addTarget:self action:@selector(clickAddBtnMethod) forControlEvents:UIControlEventTouchUpInside];
    
    [self.tabBar addSubview:cameraBtn];
    
}

#pragma mark ---- <点击了addBtn>
- (void)clickAddBtnMethod {
    self.isAlreadyUpload = NO;
    self.firstDetailModel = nil;
    
    NSLog(@"clickCameraBtn  %@", _isAlreadyUpload ? @"second" : @"first");
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    weakself(ws);
    self.popAddView = [[PopAddContentView alloc] initWithFrame:self.view.bounds];

    _popAddView.clickTypeBlock = ^(ClickType clickType) {
        if (clickType == 0) {
            
            [ws showManaualViewIsCompany:YES];
        }else if (clickType == 1) {
            
            [ws showManaualViewIsCompany:NO];
        }else if (clickType == 2) {
            [ws showScanPage];
        }
    };
    [window addSubview:self.popAddView];

}
- (void)showScanPage {
//    "takePhoto" = "拍照";
//    "choosePhoto" = "去相册选择";

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"cancel", nil)
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:NSLocalizedString(@"takePhoto", nil),
                                NSLocalizedString(@"choosePhoto", nil), nil];
    [sheet showInView:self.view];

}

- (void)showManaualViewIsCompany:(BOOL)isCompany {
    
    if (isCompany) {
        Add_Manual_CompanyViewController * companyVC = [Add_Manual_CompanyViewController new];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:companyVC];
        [self presentViewController:nav animated:YES completion:^{

        }];
        
    }else {
        Add_Manual_ContactViewController * contactVC = [Add_Manual_ContactViewController new];
        UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:contactVC];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
}
    
- (void)globalAppearanceConfig {
    // 全局导航栏标题字体
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithHex:@"3c3c3c"], NSFontAttributeName : kFontSize17}];
    
    NSDictionary *normalDic = @{NSForegroundColorAttributeName:[UIColor grayColor]};
    NSDictionary *selectedDic = @{NSForegroundColorAttributeName:[UIColor orangeColor]};
    
    [[UITabBarItem appearance] setTitleTextAttributes:normalDic forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:selectedDic forState:UIControlStateSelected];
    

    UIImage *barBgImage = [UIImage imageNamed:@"line_01"];
    [[UINavigationBar appearance] setBackgroundImage:barBgImage forBarMetrics:UIBarMetricsDefault];
    [UINavigationBar appearance].shadowImage = [UIImage new];

    // 返回按钮
    UIImage *backUpImage = [UIImage imageNamed:@"qf_back"];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[backUpImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backUpImage.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    UIImage *backDownImage = [UIImage imageNamed:@"qf_back"];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[backDownImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backDownImage.size.width, 0, 0)] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    
//    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -64) forBarMetrics:UIBarMetricsDefault];
    // 左右按钮
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor redColor], NSFontAttributeName : kFontSize15} forState:UIControlStateNormal];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { // take photo / 去拍照
        [self takePhoto];
    } else if (buttonIndex == 1) {
        [self pushTZImagePickerController];
    }
}
#pragma mark - UIImagePickerController

- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        if (iOS8Later) {
//            @"请在iPhone的""设置-隐私-相机""中允许访问相机"
//            "userCameraTip" = "請在iPhone的設置-隱私-相機中允許訪問相機";
            //            "cancel"= "取消";
            //            Setting = "设置";
//            "cannotUseCamera" = "无法使用相机";

            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"cannotUseCamera", nil)                                                                message:NSLocalizedString(@"userCameraTip", nil)
                                    delegate:self
                                                  cancelButtonTitle:
                                   NSLocalizedString(@"cancel", nil)                                                  otherButtonTitles:NSLocalizedString(@"Setting", nil), nil];
            [alert show];
        } else {
//            "confirm" = "确定";
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"cannotUseCamera", nil)   message:NSLocalizedString(@"userCameraTip", nil)
                                                           delegate:self cancelButtonTitle:
                                   NSLocalizedString(@"confirm", nil)
                                                  otherButtonTitles:nil];
            [alert show];
        }
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        if (iOS8Later) {
//            @"请在iPhone的""设置-隐私-相册""中允许访问相册"
//            "userPhotosTip" = "請在iPhone的設置-隱私-相冊中允許訪問相冊";
//            "cannotUsePhotos" = "无法使用相册";

            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:
                                   NSLocalizedString(@"cannotUsePhotos", nil)
                                                            message:NSLocalizedString(@"userPhotosTip", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"Setting", nil), nil];
            [alert show];
        } else {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"cannotUsePhotos", nil)
                                                            message:NSLocalizedString(@"userPhotosTip", nil) delegate:self cancelButtonTitle:
                NSLocalizedString(@"confirm", nil)otherButtonTitles:nil];
            [alert show];
        }
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}
// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(CLLocation *location, CLLocation *oldLocation) {
        weakSelf.location = location;
    } failureBlock:^(NSError *error) {
        weakSelf.location = nil;
    }];
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
        
    }
    return _imagePickerVc;
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
//        tzImagePickerVc.sortAscendingByModificationDate = self.sortAscendingSwitch.isOn;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:self.location completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                    }];
                }];
            }
        }];
    }
}
- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        NSLog(@"location:%@",phAsset.location);
        
        if (!self.isAlreadyUpload) {
            [self uploadFirstImage:@[image]];
        }else {
            [self uploadSecondImage:@[image]];
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    if ([picker isKindOfClass:[UIImagePickerController class]]) {
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)settingBtnClick {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}

#pragma mark - TZImagePickerController

- (void)pushTZImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc]
                                              initWithMaxImagesCount:2
                                              columnNumber:4
                                              delegate:self pushPhotoPickerVc:YES];
    imagePickerVc.showSelectBtn = NO;
    weakself(ws);
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        NSLog(@"hello %@", photos);
        
        
        if (!ws.isAlreadyUpload) {
            [ws uploadFirstImage:photos];
        }else {
            [ws uploadSecondImage:photos];
        }
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - TZImagePickerControllerDelegate

/// User click cancel button
/// 用户点击了取消
- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
     NSLog(@"cancel");
}

// The picker should dismiss itself; when it dismissed these handle will be called.
// If isOriginalPhoto is YES, user picked the original photo.
// You can get original photo with asset, by the method [[TZImageManager manager] getOriginalPhotoWithAsset:completion:].
// The UIImage Object in photos default width is 828px, you can set it by photoWidth property.
// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
// 如果isSelectOriginalPhoto为YES，表明用户选择了原图
// 你可以通过一个asset获得原图，通过这个方法：[[TZImageManager manager] getOriginalPhotoWithAsset:completion:]
// photos数组里的UIImage对象，默认是828像素宽，你可以通过设置photoWidth属性的值来改变它
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    // 1.打印图片名字
    [self printAssetsName:assets];
    // 2.图片位置信息
    if (iOS8Later) {
        for (PHAsset *phAsset in assets) {
            NSLog(@"location:%@",phAsset.location);
        }
    }
}
#pragma mark - Private

/// 打印图片名字
- (void)printAssetsName:(NSArray *)assets {
    NSString *fileName;
    for (id asset in assets) {
        if ([asset isKindOfClass:[PHAsset class]]) {
            PHAsset *phAsset = (PHAsset *)asset;
            fileName = [phAsset valueForKey:@"filename"];
        } else if ([asset isKindOfClass:[ALAsset class]]) {
            ALAsset *alAsset = (ALAsset *)asset;
            fileName = alAsset.defaultRepresentation.filename;;
        }
         NSLog(@"图片名字:%@",fileName);
        
    }
}

//上传第二张图片
- (void)uploadSecondImage:(NSArray *)images{
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kUploadSecondImageUrl];
    NSDictionary * dic = @{@"file": @"iOS"};
    
    [self showActivity:NSLocalizedString(@"正在提交", nil)];
    
    weakself(ws);
    [NetWorkHelper uploadImageWithPath:url photos:images params:dic ocrId:self.firstDetailModel.ocrId success:^(id object) {
        [ws hideAllAlert];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];
            return;
        }
        
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            Contact_DetailModel * detailModel = [Contact_DetailModel yy_modelWithJSON:object[@"obj"]];
            
            [ws pushAddContactPage:detailModel];
        });
        
    } failure:^(NSError *error) {
        
        [ws hideAllAlert];
    }];
    
//    [self pushAddContactPage:nil];

}

- (void)uploadFirstImage:(NSArray *)images {
//    [self showContinueAddAlertView];
    self.isAlreadyUpload = YES;
    
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kUploadImagesUrl ];
    NSDictionary * dic = @{@"file": @"iOS"};
    
    [self showActivity:NSLocalizedString(@"正在提交", nil)];

    weakself(ws);
    [NetWorkHelper uploadImageWithPath:url photos:images params:dic ocrId:nil success:^(id object) {
        [ws hideAllAlert];
        
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];
            return;
        }
        

        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            Contact_DetailModel * detailModel = [Contact_DetailModel yy_modelWithJSON:object[@"obj"]];
            
            ws.firstDetailModel = detailModel;
            [ws showContinueAddAlertView];
        });

    } failure:^(NSError *error) {

        [ws hideAllAlert];
    }];
    
}


- (void)showContinueAddAlertView{
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"继续上传", nil)
                                                    message:NSLocalizedString(@"继续上传", nil)
                                                   delegate:self
                                          cancelButtonTitle:
                           NSLocalizedString(@"添加B面", nil)
                                          otherButtonTitles:NSLocalizedString(@"继续创建", nil),nil];
    [alert show];
    
    self.continuAlertView = alert;
}
/*
    上传第一张
        相册
        拍照
        
        第1张上传完，弹出以下2选项
            1 继续创建完成
                进入新建联系人页面
            2 上传第二张
                相册
                拍照
 
                第二张上传完， 
                    直接进入新建页面，完成后退出
 
 */
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  {
    if (_continuAlertView == alertView) {
        
        if (buttonIndex== 0) {
            [self showScanPage];

        }else if (buttonIndex == 1) {

            [self pushAddContactPage:_firstDetailModel];
        }
        NSLog(@"%ld", buttonIndex);
    }
}



- (void)pushAddContactPage:(Contact_DetailModel *) detailModel {

    Add_Manual_ContactViewController * contactVC = [Add_Manual_ContactViewController new];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:contactVC];
    contactVC.pageStyle = PageStyleScan;
    contactVC.detailModel = detailModel;
    [self presentViewController:nav animated:YES completion:^{
        
    }];
    
}

#pragma clang diagnostic pop

#pragma mark ---- <UITabBarControllerDelegate>
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSInteger index = [self.viewControllers indexOfObject:viewController];
    NSLog(@"index = %ld  last =%ld", index, _lastSelectedIndex);
    if (index == 2) {
        [self clickAddBtnMethod];
        self.selectedIndex = _lastSelectedIndex;
    }else {    
        _lastSelectedIndex = index;
    }
}

- (void)fetchRefreshTokenMethod {
    NSLog(@"刷新token");
    UserModel * userModel = [UserModel getCurrentUserModel];
    if (!userModel) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationShowLoginVC object:kReLoginStr];
        return;
    }
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kLoginUrl];
    NSDictionary * dic = @{@"refresh_token": userModel.refresh_token};
    
    weakself(ws);
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showAlert:object[@"msg"] ? object[@"msg"] : @"" ];

            return;
        }
        
        NSDictionary * tempDic = object[@"obj"];

        if (![tempDic isKindOfClass:[NSNull class]]) {
//            UserModel * userModel = [UserModel yy_modelWithJSON:tempDic[@"user"]];
            userModel.access_token = tempDic[@"access_token"];
            userModel.refresh_token = tempDic[@"refresh_token"];
            
            [UserModel saveUserModel:userModel];
        }
        
    } failure:^(NSError *error) {
        
        [ws showWithText:kNetworkError];
    }];
}

// 跳转到登陆页面
- (void)showLoginVC:(NSNotification *)notification {
    id responseObject =  notification.object;
    
    UINavigationController * homePageNav = self.viewControllers[0];
    HomePageViewController * homePageVC = homePageNav.viewControllers[0];
    
    LoginViewController *loginVC = [LoginViewController new];
    loginVC.isPresentStyle = YES;
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
    
    weakself(ws);
    //关闭定时器
    [_timer setFireDate:[NSDate distantFuture]];
    
    loginVC.clickBlock = ^(id result) {
        homePageVC.historyType = -1;
        [homePageVC changHistoryType:0];
        [homePageVC fetchRencentBirthList];

        //如果是重新登陆，不用开启定时器
        if ([responseObject isEqualToString:kReLoginStr]) {
            return ;
        }
        //开启定时器
        [ws.timer setFireDate:[NSDate distantPast]];
    };
    
    [self presentViewController:nav animated:YES completion:^{
        [loginVC showAlert:responseObject ];
    }];
}


@end
